package top.banner.utils;

import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import top.banner.entity.JDContent;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HTMLParseUtils {

    public static void main(String[] args) {

        new HTMLParseUtils().parseJD("文言文").forEach(System.out::println);

    }


    @SneakyThrows
    public List<JDContent> parseJD(String keyword) {
        String url = "https://search.jd.com/Search?keyword=" + keyword;

        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");

        List<JDContent> list = new ArrayList<>();

        if (element == null) {
            return list;
        }
        Elements elements = element.getElementsByTag("li");
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String name = el.getElementsByClass("p-name").eq(0).text();

            list.add(new JDContent(img, name, price));
        }

        return list;
    }
}
